package com.cy.binarySearch;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.naming.spi.DirStateFactory.Result;

/**
 * 
 * TODO(二分法查找数组中目标数值下标，有重复)
 * @author changyuan
 * @date 2018年10月9日 下午2:30:30
 * @Copyright: 2018 www.birdsh.com Inc. All rights reserved.
 */
public class BinarySearch2 {
    
    public static List binarySearch(int[] source,int target){
        ArrayList resultList = new ArrayList();
        Arrays.sort(source);
        System.out.println(Arrays.toString(source));
        int start = 0;
        int end = source.length-1;
        int mid = 0;
        while(start<end){
            mid = (start+end)/2;
            System.out.println(mid);
            if(source[mid]>target){
                end = mid;    
            }else{
                if(source[mid]<target){
                    start = mid;
                }else{
                    while(source[mid-1]==source[mid]){
                        mid=mid-1;
                    }
                    resultList.add(mid);
                    while(source[mid]==source[mid+1]){
                        resultList.add(mid+1);
                        mid=mid+1;
                    }
                    return resultList;
                }
            } 
        }
        
        return resultList;
    }

    public static void main(String[] args){
       int[] array = {5,6,3,3,3,7,8,1,2,9,3};
       List result = BinarySearch2.binarySearch(array,3);
       System.out.println("结果："+result);
       
    }
}
